#include "alarmmanager.h"
#include <QDateTime>
#include <QDebug>
#include <QTimer>
#include <QCoreApplication>

AlarmManager::AlarmManager(QObject *parent) : QObject(parent),
settings(QCoreApplication::applicationDirPath() + "/eventalarmclock.ini" , QSettings::IniFormat){

    loadAlarms();
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &AlarmManager::checkAlarms);
    timer->start(10000);  // 每分钟检查
}

void AlarmManager::loadAlarms() {

    settings.beginGroup("Alarms");
    int count = settings.value("count", 0).toInt();
    for(int i=0; i<count; ++i){
        AlarmEvent event;
        event.id = settings.value(QString("id%1").arg(i)).toString();
        event.time = QTime::fromString(settings.value(QString("time%1").arg(i)).toString(), "HH:mm");
        event.message = settings.value(QString("message%1").arg(i)).toString();
        QString log;
        log += " " + event.id
                + " " + settings.value(QString("time%1").arg(i)).toString()
                + " " + settings.value(QString("message%1").arg(i)).toString();
        alarms.append(event);
        qDebug() << "AlarmManager::loadAlarms:" << log;
    }
    settings.endGroup();
}

void AlarmManager::saveAlarms() {
    settings.clear();
    settings.beginGroup("Alarms");
    settings.setValue("count", alarms.size());
    for(int i=0; i<alarms.size(); ++i){
        settings.setValue(QString("id%1").arg(i), alarms[i].id);
        settings.setValue(QString("time%1").arg(i), alarms[i].time.toString("HH:mm"));
        settings.setValue(QString("message%1").arg(i), alarms[i].message);
    }
    settings.endGroup();
        settings.sync();
}

QVector<AlarmEvent> AlarmManager::getActiveAlarms() {
    QVector<AlarmEvent> active;
    for(auto &alarm : alarms){
        if(alarm.active) active.append(alarm);
    }
    return active;
}

 void AlarmManager::addEventAlarm(const AlarmEvent &event)
 {
     alarms.append(event);
 }

void AlarmManager::checkAlarms() {
    QDateTime now = QDateTime::currentDateTime();
    for(auto &alarm : getActiveAlarms()){
        if(alarm.time.toString("HH:mm") == now.toString("HH:mm")){

            for(auto &alarm1 : getActiveAlarms()){
            QString log;
            log += " " + alarm1.id + " " + alarm1.message;
            qDebug() << "AlarmManager::loadAlarms:" << log;
            }


            // 触发托盘闪烁
//            emit startFlashing();

            emit alarmTriggered(alarm);
            qDebug() << "alarmTriggered" << alarm.time.toString("HH:mm ")
                    << alarm.message;
//            if(alarm.repeat == 0) alarm.active = false;  // 单次触发后关闭


            // 停止闪烁逻辑（5秒后）
//            QTimer::singleShot(10000, [=](){
//                emit stopFlashing();
//            });
        }
    }
}
